package com.example.module_detail

import android.graphics.Color
import android.os.Bundle
import android.view.View

import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.entity.MovieVideoEntity
import com.blankj.utilcode.util.LogUtils
import com.example.base.RouterPath
import com.example.common.event.LiveDataBus
import com.example.common.event.LiveDataBusEvent
import com.example.common.mvi.BaseMviActivity
import com.example.detail.R
import com.example.detail.databinding.ActivityDetailBinding
import com.example.module_detail.adapter.DetailViewPagerAdapter
import com.example.module_detail.entity.TabEntity
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.Danmaku
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser

@AndroidEntryPoint
@Route(path = RouterPath.PATH_DETAIL_PAGE)
class DetailActivity : BaseMviActivity<ActivityDetailBinding>() {
    @Autowired lateinit var movieEntity :MovieVideoEntity
    private var mMoviePlayer: StandardGSYVideoPlayer? = null

    private var tabList = arrayListOf<CustomTabEntity>()
    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPagerAdapter:DetailViewPagerAdapter
    private lateinit var mDanmuContext:DanmakuContext

    override fun initViews() {
        ARouter.getInstance().inject(this)
        //初始化GSYPLAYER
        mMoviePlayer = mDatabinding.moviePlayer

        mMoviePlayer?.apply {
            setUp(movieEntity.videopath, true, "")
            backButton.visibility = View.GONE
        }
        tabList.add(TabEntity("简介",0,0))
        tabList.add(TabEntity("评论",0,0))
        mDatabinding.tabLayout.setTabData(tabList)

        //给fragments添加fragment并且强转
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_DETAIL_INTRODUCE).withString("userId",
            movieEntity.userid).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_DETAIL_COMMEND).withString("itemId",movieEntity.userid)
            .navigation() as Fragment)

        mPagerAdapter = DetailViewPagerAdapter(fragments,supportFragmentManager,lifecycle)
        mDatabinding.vp2.apply {
            offscreenPageLimit = 1
            adapter = mPagerAdapter
        }
        //显示弹幕发布布局
        mDatabinding.tvDanmu.setOnClickListener{
            mDatabinding.llDanmuLayout.visibility = View.VISIBLE
        }

        mDatabinding.ivDanmuSend.setOnClickListener{
            var danmuContent = mDatabinding.etDanmuInput.editableText.toString().trim()
            if(danmuContent.isNotEmpty()){
                sendVideoDanmu(danmuContent)
            }
        }



        mDatabinding.tabLayout.setOnTabSelectListener(object:OnTabSelectListener{
            override fun onTabSelect(position: Int) {
                mDatabinding.vp2.currentItem = position
            }

            override fun onTabReselect(position: Int) {

            }
        })

        mDatabinding.vp2.registerOnPageChangeCallback(object:ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                mDatabinding.tabLayout.currentTab = position
                if(position ==1){
                    (fragments[1] as CommendFragment).loadCommendListById("7040684506063307271")
                }
            }
        })

        //初始化弹幕
        initVideoDanmu()


        //订阅视频列表相关操作
        LiveDataBus.with<LiveDataBusEvent>("movie_detail_options").observe(this@DetailActivity){
            handLiveDataEvent(it)
        }

    }

    override fun getLayoutId(): Int =R.layout.activity_detail
    private fun initVideoDanmu(){

        //创建弹幕上下文
        mDanmuContext = DanmakuContext.create()
        //准备弹幕
        mDatabinding.danmuView.prepare(object:BaseDanmakuParser(){
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        },mDanmuContext)
    }

    private fun sendVideoDanmu(msg:String){
        //清除历史弹幕
        mDatabinding.danmuView.apply {
            clear()
            removeAllDanmakus(false)
        }
        var danmakuEntity = mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_LR).apply {
            text = msg
            textSize = 35f
            textColor = Color.RED
            padding = 10
            time = 2000 //延迟时间
        }
        mDatabinding.danmuView.addDanmaku(danmakuEntity)

        //启动弹幕动画
        mDatabinding.danmuView.start()

        //清空输入框
        mDatabinding.etDanmuInput.setText("")
        mDatabinding.llDanmuLayout.visibility = View.GONE


    }

    private fun handLiveDataEvent(event: LiveDataBusEvent) {
        movieEntity = event.data as MovieVideoEntity
        when(event.type){
            1 ->{
                mMoviePlayer?.setUp(movieEntity.videopath, true, "")
                mMoviePlayer?.startPlayLogic()
            }
        }
    }


    override fun onResume() {
        super.onResume()
        mMoviePlayer?.startPlayLogic()
    }

    override fun onPause() {
        super.onPause()
        mMoviePlayer?.onVideoPause()
    }


    override fun onDestroy() {
        super.onDestroy()
        mMoviePlayer?.release()
        mMoviePlayer = null
    }
}